package com.uzai.console.service.user.impl;

import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.user.wechatuser.*;
import com.uzai.console.dto.user.wxworkuser.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.user.WxworkUserTreeInfoService;
import com.uzai.console.vo.user.wxworkuser.WxworkMinMaxCreateTimeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WxworkUserTreeInfoServiceImpl implements WxworkUserTreeInfoService {

    private Logger logger = LoggerFactory.getLogger(WxworkUserTreeInfoServiceImpl.class);

    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    /**
     * 修改个人微信会员身份
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUpdateIdentityDto
     * @return null
     */
    @Transactional
    public void updateIdentity(WxworkUpdateIdentityDto wxworkUpdateIdentityDto){
        if(wxworkUpdateIdentityDto.getId() == null || wxworkUpdateIdentityDto.getIdentityNew() == null || wxworkUpdateIdentityDto.getUserTypeNew() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUpdateIdentityDto.getId(), wxworkUpdateIdentityDto.getMerId());

        if(wxworkUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //会员类型没有变，则身份肯定不会变化，则不修改
        if(wxworkUser.getUserType().longValue() == wxworkUpdateIdentityDto.getUserTypeNew().longValue()){
            return;
        }

        Long merId = wxworkUser.getMerId();
        Long id = wxworkUser.getId();
        //旧身份
        int identityOld = wxworkUser.getIdentity().intValue();
        //新身份
        int identityNew = wxworkUpdateIdentityDto.getIdentityNew().intValue();
        //新用户类型
        Long userTypeNew = wxworkUpdateIdentityDto.getUserTypeNew();
        //上级id
        Long parentId = Tools.getLong(wxworkUser.getParentId());
        //代理id
        Long agentId = Tools.getLong(wxworkUser.getAgentId());
        //合伙人id
        Long parterId = Tools.getLong(wxworkUser.getPartnerId());

        //自己的买家树
        String parentInfo_wo = wxworkUser.getParentInfo();
        //所有下级的买家树
        String parentInfo_son = "";
        if(parentId.longValue() != 0l){
            parentInfo_son = Tools.getStrConnect(String.valueOf(id), "_", parentInfo_wo);
        }else{
            parentInfo_son = String.valueOf(id);
        }

        //自己代理树
        String agentInfo_wo = wxworkUser.getAgentInfo();
        //所有下级的代理树
        String agentInfo_son= "";
        if(agentId.longValue() != 0l){
            agentInfo_son = Tools.getStrConnect(String.valueOf(id), "_", agentInfo_wo);
        }else{
            agentInfo_son = String.valueOf(id);
        }

        //赋值新身份
        wxworkUser.setIdentity(identityNew);
        //赋值新会员类型
        wxworkUser.setUserType(userTypeNew);

        //判断旧身份类型
        if(identityOld == IdentityEnum.BUYER.getId()) { // 旧身份是买家
            //判断新身份
            if(identityNew == IdentityEnum.AGENT.getId().intValue()) { //新身份是代理

                //清空该用户自己买家信息
                wxworkUser.setParentId(0L);
                wxworkUser.setParentInfo("");

                /**买家转代理-身份往上升
                 * 1: 批量将下N级所有买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
                 * 2：修改下N级买家树（从此用户开始清空）
                 * 3: 修改下级的上级和买家树（全部清空）,以及更新下N级的代理信息
                 */
                //1: 批量将下N级买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
                wxworkUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfo_son, merId);
                //2：修改下N级买家树（从此用户开始清空）
                wxworkUserMapper.batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                wxworkUserMapper.batchUpdateParentInfo(parentInfo_son, "", merId, false);
                //3: 修改下级的上级和买家树（全部清空）
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setMerId(merId);
                wxworkUserQuery.setParentId(wxworkUser.getId());

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                //查询总数
                Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                //有总数，且最小创建时间有
                if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                            if(wxworkUserList != null && wxworkUserList.size() > 0){
                                for(WxworkUser wxworkUser_son : wxworkUserList){
                                    wxworkUser_son.setParentId(0L);   //清空上级
                                    wxworkUser_son.setParentInfo(""); //清空上级树
                                    wxworkUser_son.setAgentId(id);    //修改代理
                                    wxworkUser_son.setAgentInfo(agentInfo_son);      //修改代理树
                                    wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                    wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                    //4：将下N级代理和下N级代理的树更新
                                    String agentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                    String agentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getAgentInfo();
                                    //分俩次替换（避免替换留下"_"符合）
                                    wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                    wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                }
                            }
                        }
                    }
                }
            }else if(identityNew == IdentityEnum.PARTNER.getId().intValue()){ //新身份是合伙人

                //首先清空该用户自己上级信息,代理信息、合伙人信息
                wxworkUser.setParentId(0L);
                wxworkUser.setParentInfo("");
                wxworkUser.setAgentId(0L);
                wxworkUser.setAgentInfo("");
                wxworkUser.setPartnerId(0L); //变成合伙人，清空自己的合伙人信息

                /**买家转合伙人-身份往上升
                 * 1: 批量将下N级所有买家的合伙人设置为此Id，满足条件：A:买家树包含此ID
                 * 2：修改下N级买家树（从此用户开始清空）
                 * 3: 修改下级的上级和买家树（全部清空），更新合伙人信息
                 */
                //1: 批量将下N级所有买家的合伙人设置为此Id，满足条件：A:买家树包含此ID
                wxworkUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                //2：修改下N级买家树（从此用户开始清空）
                wxworkUserMapper.batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                wxworkUserMapper.batchUpdateParentInfo(parentInfo_son, "", merId, false);
                //3: 修改下级的上级和买家树（全部清空），更新合伙人信息
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setMerId(merId);
                wxworkUserQuery.setParentId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                //查询总数
                Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                //有总数，且最小创建时间有
                if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                            if(wxworkUserList != null && wxworkUserList.size() > 0){
                                for(WxworkUser wxworkUser_son : wxworkUserList){
                                    wxworkUser_son.setParentId(0L);   //清空上级
                                    wxworkUser_son.setParentInfo(""); //清空上级树
                                    wxworkUser_son.setPartnerId(id);    //修改合伙人
                                    wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                    wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                }
                            }
                        }
                    }
                }
            }
        }else if(identityOld == IdentityEnum.AGENT.getId()){ //旧身份是代理
            //判断新身份
            if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                /**代理转买家-身份往下降
                 *  1：修改下N级代理树(摘除此代理)
                 *  2: 修改下级代理代理信息（代理的代理）、买家信息
                 */

                //1：修改下N级代理树
                //分俩次替换（避免替换留下"_"符合）
                wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfo_son, "_" + agentInfo_wo, merId, true);
                wxworkUserMapper.batchUpdateAgentInfo(agentInfo_son, agentInfo_wo, merId, false);

                //3: 修改下级的代理和代理树
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setMerId(merId);
                wxworkUserQuery.setAgentId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                //查询总数
                Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                //有总数，且最小创建时间有
                if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                            if(wxworkUserList != null && wxworkUserList.size() > 0){
                                for(WxworkUser wxworkUser_son : wxworkUserList){
                                    //上级为空，且身份是买家
                                    if(wxworkUser_son.getParentId().longValue() == 0L && wxworkUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                        wxworkUser_son.setParentId(id);                  //修改上级
                                        wxworkUser_son.setParentInfo(parentInfo_son);    //修改上级树
                                        //将下N级上级和下N级的上级树更新
                                        String parentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                        String parentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getParentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                    }
                                    wxworkUser_son.setAgentId(agentId);           //修改新的上级代理（代理的代理）
                                    wxworkUser_son.setAgentInfo(agentInfo_wo);    //修改新的代理树（代理的代理）
                                    wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                    wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                }
                            }
                        }
                    }
                }
            }else if(identityNew == IdentityEnum.PARTNER.getId()){ //新身份是合伙人

                //首先清空该用户自己上级信息,代理信息、合伙人信息
                wxworkUser.setParentId(0L);
                wxworkUser.setParentInfo("");
                wxworkUser.setAgentId(0L);
                wxworkUser.setAgentInfo("");
                wxworkUser.setPartnerId(0L); //变成合伙人，清空自己的合伙人信息

                /**代理转合伙人-身份往上升
                 *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:代理树包含此ID，B：上级id为空；C：身份是买家
                 *  2：修改下N级代理树
                 *  3: 修改下级的代理和代理树
                 */

                //1: 批量将下N级所有的代理，将合伙人设置为此Id，满足条件：A:代理树包含此ID
                wxworkUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);

                //2：修改下N级代理树(清空截断）
                //分俩次替换（避免替换留下"_"符合）
                wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfo_son, "", merId, true);
                wxworkUserMapper.batchUpdateAgentInfo(agentInfo_son, "", merId, false);
                //3: 修改下级的代理和代理树
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setMerId(merId);
                wxworkUserQuery.setAgentId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                //查询总数
                Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                //有总数，且最小创建时间有
                if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                            if(wxworkUserList != null && wxworkUserList.size() > 0){
                                for(WxworkUser wxworkUser_son : wxworkUserList){
                                    wxworkUser_son.setAgentId(0L);                    //清空代理人
                                    wxworkUser_son.setAgentInfo("");                  //清空代理人信息
                                    wxworkUser_son.setPartnerId(id);                  //修改合伙人
                                    wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                    wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                }
                            }
                        }
                    }
                }
            }
        }else{ //旧身份是合伙人
            //判断新身份
            if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                /**合伙人转买家-身份往下降
                 *  1：清空下N合伙人信息,更新买家信息（上级不能为空，代理不能为空，且身份是买家）
                 */

                //1：清空下N合伙人信息,更新买家信息
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setMerId(merId);
                wxworkUserQuery.setPartnerId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                //查询总数
                Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                //有总数，且最小创建时间有
                if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                            if(wxworkUserList != null && wxworkUserList.size() > 0){
                                for(WxworkUser wxworkUser_son : wxworkUserList){
                                    wxworkUser_son.setPartnerId(0L);   // 清空合伙人
                                    //上级不能为空，代理不能为空，且身份是买家
                                    if(wxworkUser_son.getParentId().longValue() == 0L && wxworkUser_son.getAgentId().longValue() == 0L && wxworkUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                        wxworkUser_son.setParentId(id);                   //修改上级
                                        wxworkUser_son.setParentInfo(parentInfo_son);    //修改上级树

                                        //将下N级上级和下N级的上级树更新
                                        String parentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                        String parentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getParentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                    }
                                    wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                    wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                }
                            }
                        }
                    }
                }
            }else if(identityNew == IdentityEnum.AGENT.getId()){ //新身份是代理

                //首先清空该用户自己上级信息
                wxworkUser.setParentId(0L);
                wxworkUser.setParentInfo("");

                /**合伙人转代理-身份往下降
                 *  1：清空下N合伙人信息,更新买家信息
                 */

                //2：清空下N合伙人信息,更新买家信息
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                wxworkUserQuery.setMerId(merId);
                wxworkUserQuery.setPartnerId(id);

                //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                WxworkMinMaxCreateTimeVo wxworkMinMaxCreateTimeVo = wxworkUserMapper.findMinAndMaxCreateTime(wxworkUserQuery);
                //查询总数
                Integer count = wxworkUserMapper.findCount(wxworkUserQuery);
                //有总数，且最小创建时间有
                if(wxworkMinMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                    //则循环查询5天内的创建的会员
                    int duration = 5 * 24 * 3600;
                    List<TimeVO> timeVOList = DateUtil.getTimeScope(wxworkMinMaxCreateTimeVo.getMinCreateTime(), wxworkMinMaxCreateTimeVo.getMaxCreateTime(), duration);
                    if (timeVOList != null && timeVOList.size() > 0) {
                        for (TimeVO timeVO : timeVOList) {
                            wxworkUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                            wxworkUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                            List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(wxworkUserQuery);
                            if(wxworkUserList != null && wxworkUserList.size() > 0){
                                for(WxworkUser wxworkUser_son : wxworkUserList){
                                    wxworkUser_son.setPartnerId(0L);  // 清空合伙人
                                    //上级不能为空，代理不能为空，且身份是代理
                                    if(wxworkUser_son.getParentId().longValue() == 0L && wxworkUser_son.getAgentId().longValue() == 0L && wxworkUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()){
                                        wxworkUser_son.setAgentId(id);                   //修改代理
                                        wxworkUser_son.setAgentInfo(agentInfo_son);     //修改代理树

                                        //将下N级代理和下N级的代理树更新
                                        String agentInfoOld_Nson = String.valueOf(wxworkUser_son.getId());
                                        String agentInfoNew_Nson = wxworkUser_son.getId() + "_" + wxworkUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    }
                                    wxworkUser_son.setUpdateTime(DateUtil.getNowTime());
                                    wxworkUserMapper.updateIdentityInfo(wxworkUser_son);
                                }
                            }
                        }
                    }
                }
            }
        }
        //更新会员信息
        wxworkUser.setUpdateTime(DateUtil.getNowTime());
        wxworkUserMapper.updateIdentityInfo(wxworkUser);

    }

    /**
     * 修改上级买家-处理树
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUpdateParentDto
     * @return null
     */
    public void updateParent(WxworkUpdateParentDto wxworkUpdateParentDto){
        if(wxworkUpdateParentDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUpdateParentDto.getId(), wxworkUpdateParentDto.getMerId());

        if(wxworkUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = wxworkUser.getMerId();
        //旧上级买家id
        long parentIdOld = Tools.getLong(wxworkUser.getParentId()).longValue();
        //新上级买家
        long parentIdNew = Tools.getLong(wxworkUpdateParentDto.getParentId()).longValue();

        if(parentIdNew != parentIdOld) {//修改了上级买家
            //自己旧的买家树
            String parentInfoOld_wo = Tools.getStr(wxworkUser.getParentInfo());

            //所有下级的旧的上级买家树
            String parentInfoOld_son = null;
            if(parentIdOld != 0){
                parentInfoOld_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", parentInfoOld_wo);
            }else{
                parentInfoOld_son = String.valueOf(wxworkUser.getId());
            }
            //自己新的买家树
            String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
            //所有下级的新的买家树
            String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的

            //验证上级买家
            if(parentIdNew != 0) { //选择了上级买家
                WxworkUser wxworkUserParent_new = wxworkUserMapper.selectById(parentIdNew, wxworkUpdateParentDto.getMerId());

                //判断存不存在
                if(wxworkUserParent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }

                //判断身份
                if(wxworkUserParent_new.getIdentity() == null || wxworkUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if(wxworkUserParent_new.getId().longValue() == wxworkUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(wxworkUserParent_new.getParentInfo());
                if(parentInfo.contains(String.valueOf(wxworkUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }

                //判断新上级买家是否有上级买家，
                if(Tools.getLong(wxworkUserParent_new.getParentId()).longValue() != 0){//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(wxworkUserParent_new.getId()), "_", wxworkUserParent_new.getParentInfo());
                    wxworkUser.setParentInfo(parentInfoNew_wo);
                }else{
                    parentInfoNew_wo = String.valueOf(wxworkUserParent_new.getId());
                    wxworkUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", parentInfoNew_wo);

            }else{ //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                wxworkUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(wxworkUser.getId());
            }

            //分俩次替换（避免替换留下"_"符合）
            wxworkUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            wxworkUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);

            //修改上级id
            wxworkUser.setParentId(parentIdNew);
            //保存用户
            wxworkUserMapper.updateById(wxworkUser);
        }
    }

    /**
     * 修改代理-处理树
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUpdateAgentDto
     * @return null
     */
    public void updateAgent(WxworkUpdateAgentDto wxworkUpdateAgentDto){
        if(wxworkUpdateAgentDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUpdateAgentDto.getId(), wxworkUpdateAgentDto.getMerId());

        if(wxworkUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = wxworkUser.getMerId();

        //旧代理
        long agentIdOld = Tools.getLong(wxworkUser.getAgentId()).longValue();
        //新代理
        long agentIdNew = Tools.getLong(wxworkUpdateAgentDto.getAgentId()).longValue();

        if(agentIdNew != agentIdOld) { //表示修改了上级代理

            //自己旧的代理树
            String agentInfoOld_wo = Tools.getStr(wxworkUser.getAgentInfo());

            //所有下级旧的代理树
            String agentInfoOld_son = null;
            if (agentIdOld != 0) {
                agentInfoOld_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", agentInfoOld_wo);
            } else {
                agentInfoOld_son = String.valueOf(wxworkUser.getId());
            }
            //自己新的代理树
            String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
            //所有下级新的代理树
            String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的

            if(agentIdNew != 0 ){ //选择了上级代理，需要验证身份
                WxworkUser wxworkUserAgent_new = wxworkUserMapper.selectById(agentIdNew, wxworkUpdateAgentDto.getMerId());
                //判断存不存在
                if(wxworkUserAgent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if(wxworkUserAgent_new.getIdentity() == null || wxworkUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if(wxworkUserAgent_new.getId().longValue() == wxworkUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(wxworkUserAgent_new.getAgentInfo());
                if(agentInfo.contains(String.valueOf(wxworkUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if(Tools.getLong(wxworkUserAgent_new.getAgentId()) != 0){ //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(wxworkUserAgent_new.getId()), "_", wxworkUserAgent_new.getAgentInfo());
                    wxworkUser.setAgentInfo(agentInfoNew_wo);
                }else{
                    agentInfoNew_wo = String.valueOf(wxworkUserAgent_new.getId());
                    wxworkUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(wxworkUser.getId()), "_", agentInfoNew_wo);
            }else{ //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                wxworkUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(wxworkUser.getId());
            }

            //分俩次替换（避免替换留下"_"符合）
            wxworkUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            wxworkUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);

            //修改代理id
            wxworkUser.setAgentId(agentIdNew);
            //保存会员
            wxworkUserMapper.updateById(wxworkUser);
        }
    }

    /**
     * 修改合伙人
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkUpdatePartnerDto
     * @return null
     */
    public void updatePartner(WxworkUpdatePartnerDto wxworkUpdatePartnerDto){
        if(wxworkUpdatePartnerDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WxworkUser wxworkUser = wxworkUserMapper.selectById(wxworkUpdatePartnerDto.getId(), wxworkUpdatePartnerDto.getMerId());

        if(wxworkUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = wxworkUser.getMerId();

        //旧合伙人
        long partnerIdOld = Tools.getLong(wxworkUser.getPartnerId()).longValue();
        //新合伙人
        long partnerIdNew = Tools.getLong(wxworkUpdatePartnerDto.getPartnerId()).longValue();

        if(partnerIdOld != partnerIdNew){ //表示修改了合伙人
            //选择了合伙人，验证对方身份
            if(partnerIdNew != 0 ){
                WxworkUser wxworkUserPartner_new = wxworkUserMapper.selectById(partnerIdNew, wxworkUpdatePartnerDto.getMerId());
                //判断存不存在
                if(wxworkUserPartner_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if(wxworkUserPartner_new.getIdentity() == null || wxworkUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if(wxworkUserPartner_new.getId().longValue() == wxworkUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
            }

            //修改自己的合伙人id
            wxworkUser.setPartnerId(partnerIdNew);
            //保存会员
            wxworkUserMapper.updateById(wxworkUser);
        }
    }


}
